from langchain.chains import LLMChain
from langchain_deepseek import ChatDeepSeek
from langchain.prompts import PromptTemplate,ChatPromptTemplate
from langchain.output_parsers import StructuredOutputParser
from langchain.output_parsers import ResponseSchema
import os

def analyze_stock_deepseek(fundamentals: dict) -> dict:
    # 从环境变量中获取API密钥
    try:
        api_key = os.environ['API_KEY']
        api_base = os.environ['API_BASE']
        model_name = os.environ['MODEL_NAME']
    except KeyError:
        raise ValueError('DEEPSEEK_API_KEY未在环境变量中配置')

    llm = ChatDeepSeek(
        model=model_name,
        api_key=api_key,
        api_base=api_base,
        timeout=1800,
    )
    
    zhpj_schema = ResponseSchema(name="zhpj", description="给出该股票的综合评价，1-5星，只要给出数字")
    cwjk_schema = ResponseSchema(name="cwjk", description="给出该股票的财务健康状况，只要给出是或否")
    tzjz_schema = ResponseSchema(name="tzjz", description="给出该股票的投资价值，只要给出是或否")
    xxpj_schema = ResponseSchema(name="xxpj", description="给出该股票的基本面的详细评价")
    response_schemas = [zhpj_schema, cwjk_schema, tzjz_schema, xxpj_schema]

    output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
    format_instructions = output_parser.get_format_instructions()
    print(format_instructions)
    
     # 构建提示模板
    prompt_template = """
    作为专业股票分析师，请基于以下财务数据进行分析：
    利润表：{income_statement}
    资产负债表：{balance_sheet}
    
    请按以下结构输出：
    zhpj:给出该股票的综合评价，1-5星，只要给出数字
    cwjk:给出该股票的财务健康状况，只要给出是或否
    tzjz:给出该股票的投资价值，只要给出是或否
    xxpj:给出该股票的基本面的详细评价
    
    {format_instructions}
    """


    try:
        #chain = LLMChain(llm=llm, prompt=PromptTemplate.from_template(prompt_template))
        prompt_temp = PromptTemplate.from_template(prompt_template)
        #prompt_temp = ChatPromptTemplate.from_messages(["human",prompt_template])
        chain = prompt_temp | llm 
        response = chain.invoke({
            'income_statement': fundamentals['income_statement'],
            'balance_sheet': fundamentals['balance_sheet'],
            'format_instructions': format_instructions
        })
        print("-"*100)
        print(response)
        print("="*100)
        print(response.content)
        print("+"*100)
        
        # 解析模型响应（实际使用中需要更健壮的解析逻辑）
        return output_parser.parse(response.content)
    except Exception as e:
        raise ValueError(f"模型分析失败: {str(e)}")
